package com.huashi.dealer.modular.controller.store.user;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.StoreUser;
import com.huashi.dealer.commonEntity.User;
import com.huashi.dealer.core.page.PageFactory;
import com.huashi.dealer.core.pojo.CommonResult;
import com.huashi.dealer.modular.business.user.param.*;
import com.huashi.dealer.modular.business.user.service.UserService;
import com.huashi.dealer.modular.business.user.vo.StoreUserListItemVo;
import com.huashi.dealer.modular.business.user.vo.StoreUserLoginVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Store端用户控制器
 * PC端用户管理接口
 *
 * @author 谭陈强
 * @since 2025-08-07
 */
@Slf4j
@Tag(name = "Store端用户控制器")
@RestController("storeUserController")
@RequestMapping("/store/user")
@Validated
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/alterTable/{type}")
    @Operation(summary = "切换表格")
    public CommonResult<String> alterTable(@PathVariable int type) {
        return CommonResult.data(userService.alterTable(type));
    }
    /**
     * 账号密码登录
     */
    @PostMapping("/accountLogin")
    @Operation(summary = "账号密码登录")
    public CommonResult<UserInfo> accountLogin(@RequestParam(required = false) String account,
                                               @RequestParam(required = false) String password,
                                               @RequestParam(required = false) String code) {
        UserRequestParam requestParam = new UserRequestParam();
        requestParam.setAccount(account);
        requestParam.setPassword(password);
        requestParam.setCode(code);
        try {
            UserInfo userInfo = userService.accountLogin(requestParam);
            return CommonResult.data(userInfo);
        } catch (Exception e) {
            return CommonResult.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 用户自动登录
     */
//    @PostMapping("/login")
//    @Operation(summary = "用户自动登录")
//    public CommonResult<UserResponseParam> login(@RequestBody UserRequestParam requestParam) {
//        try {
//            UserResponseParam responseParam = userService.login(requestParam);
//            return CommonResult.data(responseParam);
//        } catch (Exception e) {
//            return CommonResult.error("登录失败：" + e.getMessage());
//        }
//    }

    /**
     * 当前用户详情
     */
    @GetMapping("/detail")
    @Operation(summary = "当前用户详情")
    public CommonResult<UserInfo> detail() {
        try {
            String token = StpUtil.getTokenValue();
            UserInfo responseParam = userService.getUserDetail(token);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 编辑用户信息
     */
    @PostMapping("/edit")
    @Operation(summary = "编辑用户信息")
    public CommonResult<String> edit(@ModelAttribute User requestParam) {
        try {
            userService.editUserInfo(requestParam);
            return CommonResult.ok("编辑成功");
        } catch (Exception e) {
            return CommonResult.error("编辑失败：" + e.getMessage());
        }
    }

    /**
     * 获取验证码
     */
    @GetMapping("/code")
    @Operation(summary = "获取验证码")
    public CommonResult<UserResponseParam> generateCode() {
        try {
            UserResponseParam responseParam = userService.generateCode();
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取验证码失败：" + e.getMessage());
        }
    }

        /**
     * 业务员登录
     */
    @PostMapping("/storeUserLogin")
    @Operation(summary = "业务员登录")
    public CommonResult<StoreUser> storeUserLogin(@RequestParam(required = false) String account,
                                                   @RequestParam(required = false) String password,
                                                   @RequestParam(required = false) String code) {
        UserRequestParam requestParam = new UserRequestParam();
        requestParam.setAccount(account);
        requestParam.setPassword(password);
        requestParam.setCode(code);
        try {
            StoreUser storeUser = userService.storeUserLogin(requestParam);
            return CommonResult.data(storeUser);
        } catch (Exception e) {
            return CommonResult.error("业务员登录失败：" + e.getMessage());
        }
    }

    /**
     * Store用户登录（包含角色权限）
     */
    @PostMapping("/login")
    @Operation(summary = "Store用户登录")
    public CommonResult<StoreUserLoginVo> login(@RequestBody UserRequestParam requestParam) {
        try {
            StoreUserLoginVo loginVo = userService.storeLogin(requestParam);
            return CommonResult.data(loginVo);
        } catch (Exception e) {
            return CommonResult.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    @Operation(summary = "获取验证码")
    public CommonResult<String> getCaptcha() {
        try {
            // 生成4位随机验证码
            String captcha = generateRandomCode(4);
            // 将验证码存储到session中
            // session.setAttribute("captcha", captcha); // This line was commented out as 'session' is not defined in this class.
            return CommonResult.data(captcha);
        } catch (Exception e) {
            return CommonResult.error("获取验证码失败：" + e.getMessage());
        }
    }

    /**
     * 生成随机验证码
     */
    private String generateRandomCode(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        java.util.Random random = new java.util.Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    /**
     * 业务员详情
     */
    @GetMapping("/storeUserDetail")
    @Operation(summary = "业务员详情")
    public CommonResult<StoreUserVo> storeUserDetail() {
        try {
            StoreUserVo responseParam = userService.getStoreUserDetail();
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取业务员详情失败：" + e.getMessage());
        }
    }

    /**
     * 业务员详情
     */
    @GetMapping("/storeUserDetail/{storeId}")
    @Operation(summary = "业务员详情")
    public CommonResult<StoreDetail> storeUserDetailById(@PathVariable Long storeId) {
        try {
            StoreDetail responseParam = userService.getStoreUserDetailById(storeId);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取业务员详情失败：" + e.getMessage());
        }
    }
    /**
     * 客户列表
     */
    @GetMapping("/customList")
    @Operation(summary = "客户列表")
    public CommonResult<CustomInfoResponseParam> customList() {
        try {
//            CustomInfoResponseParam responseParam = userService.getCustomList(page);
            return CommonResult.data(null);
        } catch (Exception e) {
            return CommonResult.error("获取客户列表失败：" + e.getMessage());
        }
    }

    /**
     * 余额申请
     */
    @PostMapping("/balanceApply")
    @Operation(summary = "余额申请")
    public CommonResult<String> balanceApply(@RequestParam(required = false) String money,
                                             @RequestParam(value = "images", required = false) String images) {
        try {
            userService.balanceApply(money, images);
            return CommonResult.ok("申请成功");
        } catch (Exception e) {
            return CommonResult.error("申请失败：" + e.getMessage());
        }
    }

    /**
     * 对账单
     */
    @GetMapping("/statementAccount")
    @Operation(summary = "对账单")
    public CommonResult<String> statementAccount(@RequestHeader(value = "token", required = false) String headerToken,
                                                           @RequestParam(value = "token", required = false) String paramToken,
                                                           @RequestParam(required = false) String startDate,
                                                           @RequestParam(required = false) String endDate,
                                                           @RequestParam(required = false) Integer isStoreType) {
        try {
            String token = headerToken != null ? headerToken : paramToken;
//            UserResponseParam responseParam = userService.getStatementAccount(token, startDate, endDate, isStoreType);
            return CommonResult.ok();
        } catch (Exception e) {
            return CommonResult.error("获取对账单失败：" + e.getMessage());
        }
    }

    // ========== Store端特有接口 ==========

    /**
     * 用户列表（分页）
     */
    @GetMapping("/list")
    @Operation(summary = "门店后台-管理员用户列表")
    public CommonResult<Page<StoreUserListItemVo>> getStoreAdminUserList(@RequestParam(required = false) Integer roleType,
                                                                         @RequestParam(required = false) Long parentId,
                                                                         @RequestParam(required = false) String keyword,
                                                                         @RequestParam String userName) {
        try {
            Page<StoreUserListItemVo> page = PageFactory.defaultPage();
            StoreUserListRequest request = new StoreUserListRequest();
            if (roleType != null) request.setRoleType(roleType);
            request.setParentId(parentId);
            request.setKeyword(keyword);
            Page<StoreUserListItemVo> result = userService.getStoreAdminUserPage(request, page,userName);
            return CommonResult.data(result);
        } catch (Exception e) {
            return CommonResult.error("获取用户列表失败：" + e.getMessage());
        }
    }

    /**
     * 新增管理员
     */
    @PostMapping("/create")
    @Operation(summary = "门店后台-新增管理员")
    public CommonResult<String> createStoreAdmin(@RequestBody StoreUserSaveRequest request) {
        try {
            userService.createStoreAdminUser(request);
            return CommonResult.ok("添加成功");
        } catch (Exception e) {
            return CommonResult.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 编辑管理员
     */
    @PutMapping("/update")
    @Operation(summary = "门店后台-编辑管理员")
    public CommonResult<String> updateStoreAdmin(@RequestBody StoreUserSaveRequest request) {
        try {
            userService.updateStoreAdminUser(request);
            return CommonResult.ok("更新成功");
        } catch (Exception e) {
            return CommonResult.error("更新失败：" + e.getMessage());
        }
    }
    /**
     * 更新StoreUser
     */
    @PutMapping("/updateStoreUser")
    @Operation(summary = "门店后台-更新StoreUser")
    public CommonResult<String> updateStoreUser(@RequestBody StoreUser user) {
        try {
            userService.updateStoreUser(user);
            return CommonResult.ok("更新成功");
        } catch (Exception e) {
            return CommonResult.error("更新失败：" + e.getMessage());
        }
    }
    /**
     * 删除管理员（软删）
     */
    @DeleteMapping("/delete/{storeUserId}")
    @Operation(summary = "门店后台-删除管理员")
    public CommonResult<String> deleteStoreAdmin(@PathVariable Long storeUserId) {
        try {
            userService.deleteStoreAdminUser(storeUserId);
            return CommonResult.ok("删除成功");
        } catch (Exception e) {
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 用户统计
     */
    @GetMapping("/statistics")
    @Operation(summary = "用户统计")
    public CommonResult<Object> getUserStatistics() {
        try {
            // TODO: 实现用户统计逻辑
            return CommonResult.data("用户统计信息");
        } catch (Exception e) {
            return CommonResult.error("获取用户统计失败：" + e.getMessage());
        }
    }

    @GetMapping("/roles")
    @Operation(summary = "门店后台-获取角色列表", description = "获取所有可用的角色列表，用于新增/编辑管理员时选择角色")
    public CommonResult<List<RoleListItemVo>> getRoleList(@RequestParam(required = false) String roleName) {
        try {
            List<RoleListItemVo> roles = userService.getRoleList(roleName);
            return CommonResult.data(roles);
        } catch (Exception e) {
            return CommonResult.error("获取角色列表失败：" + e.getMessage());
        }
    }

    @GetMapping("/managers")
    @Operation(summary = "门店后台-获取业务员主管列表", description = "获取所有业务员主管列表，用于新增/编辑管理员时选择上级主管")
    public CommonResult<List<ManagerListItemVo>> getManagerList() {
        try {
            List<ManagerListItemVo> managers = userService.getManagerList();
            return CommonResult.data(managers);
        } catch (Exception e) {
            return CommonResult.error("获取业务员主管列表失败：" + e.getMessage());
        }
    }
}
